package org.eddm.list;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.io.IOException;

import javax.swing.JPanel;

import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.svg.SVGDocument;

public class EDDMCellItem extends JPanel{	
	
	private GraphicsNode rootGN;	
	
	public EDDMCellItem(String uri) throws IOException {		
		setSvgUri(uri);
		setPreferredSize(new Dimension(100,100));
	}
	
	public EDDMCellItem() {
		setPreferredSize(new Dimension(100,100));
	}

	public void setSvgUri(String uri) throws IOException {
		String parser = XMLResourceDescriptor.getXMLParserClassName();
		SAXSVGDocumentFactory df = new SAXSVGDocumentFactory(parser);
		SVGDocument doc = df.createSVGDocument(uri);
		UserAgent userAgent = new UserAgentAdapter();
		DocumentLoader loader = new DocumentLoader(userAgent);
		BridgeContext ctx = new BridgeContext(userAgent, loader);
		ctx.setDynamicState(BridgeContext.DYNAMIC);
		GVTBuilder builder = new GVTBuilder();
		rootGN = builder.build(ctx, doc);		
    }
	
	@Override
	public void paint(Graphics g) {		
		super.paint(g);
		if (null != rootGN) {			
			Rectangle2D svgSize = rootGN.getBounds();
			
			double height = svgSize.getHeight();
			double weight = svgSize.getWidth();
			
			double sx = 1;
			double sy = 1;
			
			if(height>80)
				sy = 80/height;
			if(weight>80)
				sx = 80/weight;
			
			double rescale = Math.min(sx, sy);
			
			double translateY = 10;
			if(height<80)
				translateY = (100-(height))/2;
			
			double translateX = 10;
			if(weight<80)
				translateX = (100-(weight))/2;
			
			AffineTransform translate = AffineTransform.getTranslateInstance(translateX, translateY );
			AffineTransform afScale = AffineTransform.getScaleInstance(rescale, rescale);
			translate.concatenate(afScale);
			
			rootGN.setTransform(translate);			
			rootGN.paint((Graphics2D)g);
		}
	}
		
}
